package com.pay.channel.factory;

import com.pay.channel.spi.ChannelAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class ChannelAdapterFactory {
    
    private final Map<String, ChannelAdapter> adapterMap = new ConcurrentHashMap<>();
    
    @Autowired
    public ChannelAdapterFactory(List<ChannelAdapter> adapters) {
        // 初始化所有渠道适配器
        for (ChannelAdapter adapter : adapters) {
            String channelName = adapter.getChannelName();
            adapterMap.put(channelName, adapter);
            log.info("注册渠道适配器：{}", channelName);
        }
    }
    
    /**
     * 获取渠道适配器
     */
    public ChannelAdapter getAdapter(String channelName) {
        if (channelName == null || channelName.trim().isEmpty()) {
            throw new IllegalArgumentException("渠道名称不能为空");
        }
        
        ChannelAdapter adapter = adapterMap.get(channelName.toUpperCase());
        if (adapter == null) {
            throw new IllegalArgumentException("不支持的支付渠道：" + channelName);
        }
        
        return adapter;
    }
    
    /**
     * 获取所有支持的渠道
     */
    public List<String> getSupportedChannels() {
        return List.copyOf(adapterMap.keySet());
    }
    
    /**
     * 检查渠道是否支持
     */
    public boolean isChannelSupported(String channelName) {
        return channelName != null && adapterMap.containsKey(channelName.toUpperCase());
    }
}



